<script setup lang="ts">
import { onMounted, onUnmounted, ref, watch } from 'vue'
import { init as initEChart, type ECharts, type EChartsOption, type SeriesOption } from 'echarts'
import { getEntity } from '../../base'
import {
  SpeedUnit,
  SpeedUnitSelect,
  LengthUnit,
  LengthUnitSelect,
  fromMpsConvert,
  fromMeterConverter,
  lengthUnitName,
  speedUnitName
} from '@/widgets'
import type { AircraftType, RateItem } from '../types'

const props = defineProps<{
  id: string
  stage: 'Climb' | 'Descent'
}>()

const altUnit = ref<LengthUnit>(LengthUnit.FT)
const spdUnit = ref<SpeedUnit>(SpeedUnit.FTPM)

let rateList: RateItem[] = []
function initData() {
  const acType = getEntity<AircraftType>('AircraftType', props.id)
  const stage = props.stage
  if (acType) {
    if (stage === 'Climb') {
      rateList = acType.climbRateList
    } else {
      rateList = acType.descendRateList
    }
  }
}

const chartEl = ref<HTMLDivElement>()
let chart: ECharts | null = null

function updateChart() {
  if (!chart) {
    return
  }
  const series = makeSeries()
  const opts: EChartsOption = {
    title: {
      left: 'right',
      text: `${props.id}${props.stage === 'Climb' ? '爬升率' : '下降率'}/高度`,
      subtext: '大气模型:ISA'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br /> {c}',
      axisPointer: { type: 'cross' }
    },
    legend: {
      data: ['norm', 'max']
    },
    series,
    xAxis: {
      name: `高度(${lengthUnitName(altUnit.value)})`,
      type: 'value'
    },
    yAxis: {
      name: `速度(${speedUnitName(spdUnit.value)})`,
      type: 'value'
    }
  }

  chart.clear()
  chart.setOption(opts)
}

function makeSeries(): SeriesOption[] {
  const altFn1 = fromMeterConverter(altUnit.value)
  const altFn = (e: number) => Math.floor(altFn1(e))
  const spdFn1 = fromMpsConvert(spdUnit.value)
  const spdFn = (e: number) => Math.floor(spdFn1(e) * 100.0) / 100.0
  const lst = rateList
  return [
    {
      type: 'line',
      name: 'norm',
      data: lst.map((e) => [altFn(e.altitude), spdFn(e.norm)])
    },
    {
      type: 'line',
      name: 'max',
      data: lst.map((e) => [altFn(e.altitude), spdFn(e.max)])
    }
  ]
}

onMounted(() => {
  initData()
  chart = initEChart(chartEl.value)
  updateChart()
})
onUnmounted(() => {
  chart?.dispose()
})

watch(spdUnit, updateChart)
watch(altUnit, updateChart)
</script>
<template>
  <div class="act-rate-view">
    <div class="row">
      <div class="txt-box col-5em">速度单位</div>
      <SpeedUnitSelect
        v-model="spdUnit"
        :options="[SpeedUnit.MPS, SpeedUnit.FTPM, SpeedUnit.KT]"
        style="margin-right: 3em"
      />
      <div class="txt-box col-5em">高度类型</div>
      <LengthUnitSelect v-model="altUnit" :options="[LengthUnit.M, LengthUnit.FT]" />
    </div>
    <div class="rate-chart" ref="chartEl"></div>
  </div>
</template>
<style lang="scss">
.act-rate-view {
  .rate-chart {
    margin-top: 2em;
    width: 50em;
    height: 40em;
  }
}
</style>
